package online.afeibaili.storebackendframework.util

import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.io.FileOutputStream
import java.net.URL
import java.net.URLConnection
import java.util.*

private const val IMAGE_PATH_NAME = "/image"
private const val VIDEO_PATH_NAME = "/video"

//在image下
private const val AVATAR_PATH_NAME = "/avatar"
private const val PRODUCT_PATH_NAME = "/product"

val IMAGES_PATH = "${System.getProperty("user.dir")}$IMAGE_PATH_NAME"
val VIDEO_PATH = "${System.getProperty("user.dir")}$VIDEO_PATH_NAME"

fun saveImage(file: MultipartFile): String {
    File(IMAGES_PATH).mkdirs()
    val filePath = "${System.currentTimeMillis()}-${file.originalFilename}"
    file.transferTo(File("$IMAGES_PATH/$filePath"))
    return "$IMAGE_PATH_NAME/$filePath"
}

fun saveVideo(file: MultipartFile): String {
    File(VIDEO_PATH).mkdirs()
    val filePath = "${System.currentTimeMillis()}-${file.originalFilename}"
    file.transferTo(File("$VIDEO_PATH/$filePath"))
    return "$VIDEO_PATH_NAME/$filePath"
}

fun saveAvatar(nickName: String, url: String): String {
    File("$IMAGES_PATH$AVATAR_PATH_NAME").mkdirs()
    val connection: URLConnection = URL(url).openConnection()
    val fileName = "$nickName-${System.currentTimeMillis()}.jpg"
    val fileOutputStream = FileOutputStream(File("$IMAGES_PATH$AVATAR_PATH_NAME/$fileName"))
    fileOutputStream.write(connection.getInputStream().readBytes())
    fileOutputStream.close()
    return "$IMAGE_PATH_NAME$AVATAR_PATH_NAME/$fileName"
}

fun saveProductImage(file: File): String {
    val fileDirection = File("$IMAGES_PATH$PRODUCT_PATH_NAME")
    fileDirection.mkdirs()
    val extension: String = file.extension
    val fileName: String = UUID.randomUUID().toString() + ".$extension"
    file.copyTo(File("${fileDirection.path}/${fileName}"))

    return "$IMAGE_PATH_NAME$PRODUCT_PATH_NAME/$fileName"
}